package cn.pugle.mianshi.thread1To10;

import static cn.pugle.mianshi.thread1To10.Constant.MAX;

/**
 * <p> Created by tzp on 2017/9/6.
 */
public class PrintToTen1 implements Runnable {
    private int count = 1;
    private final Object lock = new Object();

    @Override
    public void run() {
        System.out.println(Thread.currentThread() + " Hello World");

        Thread thread1 = new Thread(() -> {
            while (count <= MAX) {
                synchronized (lock) {
                    if (count % 2 == 0 && count <= MAX) {
                        System.out.println(Thread.currentThread() + " " + count++);
                    }
                }
                Thread.yield();
            }
        });
        thread1.start();

        Thread thread2 = new Thread(() -> {
            while (count <= MAX) {
                synchronized (lock) {
                    if (count % 2 == 1 && count <= MAX) {
                        System.out.println(Thread.currentThread() + " " + count++);
                    }
                }
                Thread.yield();
            }
        });
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new PrintToTen1().run();
    }


    /**
     * 测试用
     */
    public void run1() {
        Thread thread2 = new Thread(() -> {
            try {
                while (true) {
                    System.out.println("hehe");
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
//        thread2.setDaemon(true);
        thread2.start();
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
